package com.bit.cfdi.web.vm;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.Init;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.WireVariable;

import com.bit.cfdi.web.constants.CFDIConstants;
import com.bit.cfdi.web.domain.DBConstants;
import com.bit.cfdi.web.domain.Usuario;
import com.bit.cfdi.web.services.UsuarioService;
import com.bit.cfdi.web.session.SessionUtils;

@VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class)
public class ActivarViewModel {
	
	private Logger log = LogManager.getLogger(this.getClass().getName());

	//Spring autowired variables
	@WireVariable
	private UsuarioService usuarioService;
	@WireVariable
	private SessionUtils sessionUtils;
	
	//Variables
	private String email;
	private String codigoActivacion;
	
	//Getters - Setters
	public String getCodigoActivacion() {
		return codigoActivacion;
	}
	
	public void setCodigoActivacion(final String codigoActivacion) {
		this.codigoActivacion = codigoActivacion;
	}
	
	@Init
	public void init(@ContextParam(ContextType.EXECUTION) Execution execution) {
		email = execution.getParameter("email");
	}
	
	//Local Commands
	@Command
	public void doActivation() {
		if(email == null || !email.matches(CFDIConstants.EMAIL_PATTERN)) {
			log.warn("WARN: invalid email");
			return;
		}
		Usuario usuario = usuarioService.getByEmail(email);
		if(usuario == null) {
			log.warn("WARN: user doesn't exist");
			return;
		}
		if(usuario.getCodigoActivacion() == null) {
			log.error("FATAL ERROR: user doesn't have validation code");
			return;
		}
		if(usuario.getStatus().intValue() == DBConstants.STATUS_ACTIVE) {
			log.warn("WARN: user already activated nothing to do");
			finishActivation(usuario);
			return;
		}
		if(usuario.getCodigoActivacion().equals(codigoActivacion)) {
			log.info("activating user: "+email);
			usuario.setStatus(DBConstants.STATUS_ACTIVE);
			usuarioService.save(usuario);
			log.info("user: " + email + " activated");
			finishActivation(usuario);
		}
	}
	
	//Private methods
	private void finishActivation(final Usuario usuario) {
		if(sessionUtils.addToSession(SessionUtils.USUARIO, usuario)) {
			Executions.getCurrent().sendRedirect(
					CFDIConstants.CFDIPages.HOME_URL);
		}
	}
}
